"use strict";
/* Controllers */
app.controller("basicDashboardController", ['$scope', '$location', '$rootScope', '$routeParams', 'basicDashboardService', '$q', function ($scope, $location, $rootScope, $routeParams, basicDashboardService, $q) {
    var vm = $scope.vm = {};
    vm.p = {};
    vm.p.biz = $routeParams.biz;
    vm.p.appdiv = $routeParams.appdiv;

    vm.p.platform = 'ALL'
    // vm.p.appdiv = 'zhaopinzhe';

    var datePicker = $('.date');
    datePicker.datetimepicker({
        locale: 'zh-cn',
        format: 'YYYY-MM-DD'
    });
    datePicker.on('dp.hide', function (e) {
        var currentInput = $(e.currentTarget).find('input');
        var eName = currentInput.attr('name');
        var p = $scope.vm.p;
        p[eName] = currentInput.val();
        $scope.$apply()
    });

    if ($scope.vm.p.bizTime == '' || typeof ($scope.vm.p.bizTime) == 'undefined') {
        $scope.vm.p.bizTime = new Date(new Date().getTime() - 86400000).format('yyyy-MM-dd');
    }

    var errorFn = function (result) {
        alert(result);
    };

    // // 查询指标列表
    // $scope.listMetricAll = function () {
    //     var vm = $scope.vm;
    //     var params = vm.p;
    //     var procFn = function (response) {
    //         var data = response.data;
    //         if (data == null) {
    //             alert("请求失败：" + response.message);
    //             return;
    //         }
    //         vm.metricList = data;
    //     };
    //     return basicDashboardService.listMetricAll(params, procFn, errorFn);
    // };

    // 查询指标列表
    $scope.listWebMetricAll = function () {
        var vm = $scope.vm;
        var params = vm.p;
        var procFn = function (response) {
            var data = response.data;
            if (data == null) {
                alert("请求失败：" + response.message);
                return;
            }
            $scope.initTreeGird(data)
        };
        // todo: 取数逻辑感觉有问题, 感觉可以下线
        return basicDashboardService.listWebMetricAll(params, procFn, errorFn);
    };

    $scope.listAllMetricSeries = function () {
        var vm = $scope.vm;
        var params = vm.p;
        var procFn = function (response) {
            var data = response.data;
            if (data == null) {
                alert("请求失败：" + response.message);
                return;
            }
            vm.allChartMetrics = data
        };
        return basicDashboardService.listAllMetricSeries(params, procFn, errorFn);
    };

    function initChart(dom, data, title) {

        var dateList = data.map(function (item) {
            return item[0];
        });
        var valueList = data.map(function (item) {
            return item[1];
        });
        // var dom = document.getElementById("container");
        var myChart = echarts.init(dom);
        window.onresize = function () {
            myChart.resize();
        };
        var option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'cross' }
            },
            legend: {
            },
            dataZoom: [{}],
            xAxis: {
                type: 'category',
                data: dateList
            },
            yAxis: [
                {
                    name: '指标值',
                    type: 'value'
                }
            ],
            series: [
                {
                    name: title,
                    yAxisIndex: 0,
                    data: valueList,
                    type: 'line',
                    smooth: true
                }
            ]
        };
        window.onresize = function () {
            myChart.resize();
        };
        if (option && typeof option === 'object') {
            myChart.setOption(option);
        }
    }

    // $scope.repeatFinish = function () {
    //     $scope.$apply();
    //     var jqDataChart = $('#dapan_charts').find('div[data-chart-key]');
    //     $.each(jqDataChart, function (i, dom) {
    //         var metaKey = $(dom).attr('data-chart-key');
    //         var chartEntity = $scope.vm.allChartMetrics.find(function (x) {
    //             return x.metaId == metaKey;
    //         });
    //         initChart(dom, chartEntity.chartData, chartEntity.indexTitle)
    //     })
    // };

    // $scope.listDashboardDimData = function () {
    //     var params = {};
    //     params = vm.p;
    //     var procFn = function (response) {
    //         var data = response.data;
    //         if (data == null) {
    //             alert("请求失败：" + response.message);
    //             return;
    //         }
    //         $scope.vm.dashboardDimData = data
    //     };
    //     return basicDashboardService.listDashboardDimData(params, procFn, errorFn);
    // };
    //
    //$scope.initTables = function () {
    //    $scope.$apply();
    //    var dashboardDimData = $scope.vm.dashboardDimData;
    //    for(var i in dashboardDimData) {
    //        var item = dashboardDimData[i];
    //        var columns = [];
    //        for(var k in item.columnNames) {
    //            var element = item.columnNames[k];
    //            var column = {};
    //            column.title = element;
    //            column.field = element;
    //            column.sortable = true;
    //            columns.push(column)
    //        }
    //        columns[0].width=100;
    //        var tableData = item.tableData;
    //        var $table = $("#list_table_" + item.configId);
    //        $table.bootstrapTable('destroy').bootstrapTable({
    //            columns: columns,
    //            data: tableData
    //        })
    //    }
    //};

    $scope.getChartByMetaId = function (metaKey) {
        var chartEntity = $scope.vm.allChartMetrics.find(function (x) {
            return x.metaId == metaKey;
        });
        var dom = document.getElementById('dapan_chart');
        initChart(dom, chartEntity.chartData, chartEntity.indexTitle)
    };

    $scope.queryDashboard = function () {
        $('#dashboard_table').bootstrapTable("showLoading")
        $("#refreshTable").addClass('disabled');
        //$scope.listDashboardDimData();
        // 先获取序列
        $scope.listAllMetricSeries().then(function () {
            // 查询指标列表
            return $scope.listWebMetricAll()
        }).then(function () {
            $('#dashboard_table').bootstrapTable("hideLoading")
            $("#refreshTable").removeClass('disabled');
        })
    };

    $scope.initTreeGird = function (tableData) {


        // let mydata = JSON.parse(
        //     '[{"vid":1,"pvid":0,"status":1,"indexTitle":"用户管理","content":"open:user:manage"},' +
        //     '{"vid":2,"pvid":0,"status":1,"indexTitle":"系统管理","content":"open:system:manage"},' +
        //     '{"vid":3,"pvid":1,"status":1,"indexTitle":"新增用户","content":"open:user:add"},' +
        //     '{"vid":4,"pvid":1,"status":1,"indexTitle":"修改用户","content":"open:user:edit"},' +
        //     '{"vid":5,"pvid":1,"status":0,"indexTitle":"删除用户","content":"open:user:del"},' +
        //     '{"vid":6,"pvid":2,"status":1,"indexTitle":"系统配置管理","content":"open:systemconfig:manage"}]')


        // let mydata = JSON.parse(
        //     '[{"vid":"test","pvid":"0","status":1,"indexTitle":"用户管理","content":"open:user:manage"},' +
        //     '{"vid":"2","pvid":"0","status":1,"indexTitle":"系统管理","content":"open:system:manage"},' +
        //     '{"vid":"3","pvid":"test","status":1,"indexTitle":"新增用户","content":"open:user:add"},' +
        //     '{"vid":"4","pvid":"test","status":1,"indexTitle":"修改用户","content":"open:user:edit"},' +
        //     '{"vid":"5","pvid":"test","status":0,"indexTitle":"删除用户","content":"open:user:del"},' +
        //     '{"vid":"6","pvid":"2","status":1,"indexTitle":"系统配置管理","content":"open:systemconfig:manage"}]')


        // let tableData = []
        // if (data.length > 0) {
        //     tableData = JSON.parse(data);
        // }

        var $table = $('#dashboard_table')
        $table.bootstrapTable('destroy').bootstrapTable({
            // url: 'json/treegrid.json',
            data: tableData,
            // dataType: 'jsonp',
            // showColumns: true,
            columns: [
                {
                    field: 'indexTitle',
                    title: '指标',
                    formatter: 'titleFormatter'
                },
                {
                    field: 'content',
                    title: '当前值',
                },
                {
                    field: 'contentInc1',
                    title: '涨幅t+1',
                    formatter: 'metricPercentFmt'
                },
                {
                    field: 'contentInc7',
                    title: '涨幅t+7',
                    formatter: 'metricPercentFmt'
                }
            ],
            treeShowField: 'indexTitle',
            idField: 'vid',
            parentIdField: 'pVid',
        })

        var columns = $table.bootstrapTable('getOptions').columns

        if (columns && columns[0][0].visible) {
            $table.treegrid({
                initialState: 'collapsed',
                expanderExpandedClass: 'glyphicon glyphicon-minus',  // 展开时，图标样式
                expanderCollapsedClass: 'glyphicon glyphicon-plus', // 折叠时，图标样式
                treeColumn: 0,
                onChange: function () {
                    $table.bootstrapTable('resetView')
                }
            })
        }
    }

    $scope.queryDashboard()

}]);


function titleFormatter(value, row, index) {


    let funcStr = "getChartByMetaId('" + row.metaID + "')"
    return '<a href="javascript:void(0)" onclick="angular.element(this).scope().' + funcStr + '">' + value + '</a>'
}

function metricPercentFmt(value, row, index) {
    if (value == null) return '-';
    let num = value * 100
    return num.toFixed(2) + '%';
}


function thisStatusFormatter(value, row, index) {
    if (value === 1) {
        return '<span class="label label-success">正常</span>'
    }
    return '<span class="label label-default">锁定</span>'
}

//自定义指令实现ng-repeat完成后执行repeatFinish方法
//app.directive('myRepeatFinish', function () {
//    return {
//        restrict: 'A',
//        link: function (scope, element, attr) {
//            console.log(scope.$index);
//            if (scope.$last == true) {
//                console.log('ng-repeat over, will draw chart.');
//                scope.$eval(attr.myRepeatFinish)
//            }
//        }
//    }
//});

/* Services */
app.service('basicDashboardService', ['ajaxService', function (ajaxService) {
    this.listAllMetricSeries = function (params, successFunction, errorFunction) {
        params.appDiv = params.appdiv;
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/web_dapan/listAllMetricSeries.do", successFunction, errorFunction);
    };

    this.listWebMetricAll = function (params, successFunction, errorFunction) {
        params.appDiv = params.appdiv;
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/web_dapan/listWebMetricAll.do", successFunction, errorFunction);
    };

    this.listMetricAll = function (params, successFunction, errorFunction) {
        params.appDiv = params.appdiv;
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/web_dapan/listMetricAll.do", successFunction, errorFunction);
    };

    this.listDashboardDimData = function (params, successFunction, errorFunction) {
        params.appDiv = params.appdiv;
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/web_dapan/listDashboardDimData.do", successFunction, errorFunction);
    };

}]);

